<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .box {
            margin: 5px 0px;
            height: 100px;
            position: relative;
        }
        
        .box-case {
            height: 100px;
            width: 100px;
            background-image: linear-gradient(to bottom right, #B58EFF, #32FF86);
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box-case"></div>
    </div>

    <div class="operation">
        <button class="begin">开始移动</button>
        <button class="terminate">停止移动</button>
    </div>

    <script>
        let operation = document.querySelector('.operation')
        let box = document.querySelector('.box')
        let box_case = document.querySelector('.box-case')


        operation.addEventListener('click', (e) => {

            // 开始移动
            if (e.target.className === 'begin') {
                move.getMove(0)
            }


            // 停止移动
            if (e.target.className === 'terminate') {
                move.getMove(1)
            }
        })


        // 闭包
        let move = (function() {
            // 定时器
            let time = null
                // 移动距离
            let num = 0

            return {
                getMove: function(status) {
                    // 停止定时器
                    if (status != 0) return clearInterval(time)

                    // 清除定时器
                    clearInterval(time)

                    // 距离单位
                    let distance = 10
                        // 开启定时器 开始移动
                    time = setInterval(() => {
                        // 如果移动的距离小于移动实体长度 距离+
                        if (num < 0) distance = Math.abs(distance) // 更改距离单位，将负数转正数
                        num += distance
                        box_case.style.left = num + 'px'

                        // 移动距离 > (总距离 - 实体长度的距离)   反向移动           
                        if (num > box.clientWidth - box_case.clientWidth) distance = -distance // 更改距离单位，将正数转负数
                    }, 10)
                }

            }
        })()
    </script>

</body>

</html>